import pygame
from signal_slot import Signal



class Timer:
    """
    倒数计时器。
    """

    def __init__(self, duration: int = 200) -> None:
        self.__duration: int = duration
        self.__last_ticks: int = 0
        self.__alive: bool = False
        self.__one_shot: bool = False
        self.__shot_count: int = 0
        
        self.timeout_signal = Signal()

    def update(self) -> None:
        if not self.__alive:
            return
        
        if pygame.time.get_ticks() - self.__last_ticks >= self.__duration:
            self.timeout_signal.emit()
            self.__last_ticks = pygame.time.get_ticks()
            self.__shot_count += 1
        
        if self.__one_shot and self.__shot_count == 1:
            self.__alive = False

    def start(self) -> None:
        self.__alive = True
        self.__last_ticks = pygame.time.get_ticks()

    def stop(self) -> None:
        self.__alive = False

    def alive(self) -> bool:
        return self.__alive

    @property
    def one_shot(self) -> bool:
        return self.__one_shot
    
    @one_shot.setter
    def one_shot(self, value: bool) -> None:
        self.__one_shot = value
